package com.xlh.virtualization.dao.helper;

import com.xlh.virtualization.dao.ImageAllocationMapper;
import com.xlh.virtualization.domain.ImageAllocation;
import com.xlh.virtualization.domain.example.ImageAllocationExample;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cheer
 */
@Repository
public class ImageAllocationMapperHelper {

    @Autowired
    private ImageAllocationMapper imageAllocationMapper;

    public void deleteByContext(Integer contextType, Long contextId) {
        ImageAllocationExample example = new ImageAllocationExample();
        example.or().andContextTypeEqualTo(contextType)
                .andContextIdEqualTo(contextId)
                .andDeletedEqualTo(false);
        ImageAllocation imageAllocation = ImageAllocation.builder()
                .deleted(true)
                .build();
        imageAllocationMapper.updateByExampleSelective(imageAllocation, example);
    }


    public void updateImage(Integer contextType, Long contextId, Long imageId) {
        ImageAllocationExample example = new ImageAllocationExample();
        example.or().andContextTypeEqualTo(contextType)
                .andContextIdEqualTo(contextId)
                .andDeletedEqualTo(false);
        ImageAllocation imageAllocation = ImageAllocation.builder()
                .imageId(imageId)
                .build();
        imageAllocationMapper.updateByExampleSelective(imageAllocation, example);
    }

    public ImageAllocation getByContext(Integer contextType, Long contextId) {
        ImageAllocationExample example = new ImageAllocationExample();
        example.or().andContextTypeEqualTo(contextType)
                .andContextIdEqualTo(contextId)
                .andDeletedEqualTo(false);
        List<ImageAllocation> imageAllocationList = imageAllocationMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(imageAllocationList)) {
            return imageAllocationList.get(0);
        }
        return null;
    }

    public List<ImageAllocation> listByContext(Integer contextType, List<Long> contextIds) {
        if (CollectionUtils.isEmpty(contextIds)) {
            return new ArrayList<>();
        }
        ImageAllocationExample example = new ImageAllocationExample();
        example.or().andContextTypeEqualTo(contextType)
                .andContextIdIn(contextIds)
                .andDeletedEqualTo(false);
        return imageAllocationMapper.selectByExample(example);
    }

    public void trueDeleteByContext(Integer contextType, Long contextId) {
        ImageAllocationExample example = new ImageAllocationExample();
        example.or().andContextTypeEqualTo(contextType)
                .andContextIdEqualTo(contextId);
        imageAllocationMapper.deleteByExample(example);
    }
}
